package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 公共控制器
 *
 * @author liudo
 * @version 1.0
 * @project sky-take-out
 * @date 2024/2/4 11:40:12
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "公共控制器")
@Slf4j
@RequiredArgsConstructor
public class CommonController {

    private final AliOssUtil aliOssUtil;

    /**
     * 上载
     *
     * @param file 文件
     * @return {@link Result}<{@link String}>
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        try {
            byte[] bytes = file.getBytes();
            // objectName 是阿里云上的文件的名称
            String uuid = UUID.randomUUID().toString();
            String originalFilename = file.getOriginalFilename();
            String newFileName = "liliudong/" + uuid + originalFilename.substring(originalFilename.lastIndexOf("."));
            String url = aliOssUtil.upload(bytes, newFileName);
            return Result.success(url);
        } catch (IOException e) {
           log.error(e.getMessage(), e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
